package com.iweb.auth;

import com.iweb.constant.AuthUrl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 处理认证： 处理用户信息的认证
 */
@WebFilter(value = "/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 拿到session
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        // 验证url : 不归这个Filter管的 直接放行
        if (!AuthUrl.values.validateUrl(req.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        // 进行用户的认证
        // 从session中获取用户
        Object result = session.getAttribute("user");
        // 如果用户不在线，则返回登录视图
        if (result == null) {
            req.getRequestDispatcher("/views/user/login/login.jsp").forward(req, resp);
            return;
        }
        // 如果用户在线则放行
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // nothing
    }
}
